package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// CleaningRecord 保洁记录模型
type CleaningRecord struct {
	BaseModel
	StoreId       int64     `orm:"column(store_id)" json:"store_id"`           // 门店ID
	VenueId       int64     `orm:"column(venue_id)" json:"venue_id"`           // 场地ID
	OrderId       int64     `orm:"column(order_id);null" json:"order_id"`      // 关联订单ID
	CleanerId     int64     `orm:"column(cleaner_id);null" json:"cleaner_id"`  // 保洁人员ID
	Status        int8      `orm:"default(1)" json:"status"`                   // 状态 1:待处理 2:进行中 3:已完成 4:已取消
	StartTime     time.Time `orm:"type(datetime)" json:"start_time"`           // 保洁开始时间
	EndTime       time.Time `orm:"type(datetime);null" json:"end_time"`        // 保洁结束时间
	ActualEndTime time.Time `orm:"type(datetime);null" json:"actual_end_time"` // 实际结束时间
	Remarks       string    `orm:"type(text);null" json:"remarks"`             // 备注
	Store         *Store    `orm:"-" json:"store,omitempty"`
	Venue         *Venue    `orm:"-" json:"venue,omitempty"`
	Cleaner       *Cleaner  `orm:"-" json:"cleaner,omitempty"`
}

// TableName 设置表名
func (cr *CleaningRecord) TableName() string {
	return "ss_cleaning_record"
}

// AddCleaningRecord 添加保洁记录
func AddCleaningRecord(cr *CleaningRecord) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(cr)
	return id, err
}

// GetCleaningRecordById 根据ID获取保洁记录
func GetCleaningRecordById(id int64) (*CleaningRecord, error) {
	o := orm.NewOrm()
	record := &CleaningRecord{BaseModel: BaseModel{Id: id}}
	err := o.Read(record)
	if err != nil {
		return nil, err
	}

	// 加载关联数据
	if record.StoreId > 0 {
		store := &Store{BaseModel: BaseModel{Id: record.StoreId}}
		if err := o.Read(store); err == nil {
			record.Store = store
		}
	}

	if record.VenueId > 0 {
		venue := &Venue{BaseModel: BaseModel{Id: record.VenueId}}
		if err := o.Read(venue); err == nil {
			record.Venue = venue
		}
	}

	if record.CleanerId > 0 {
		cleaner := &Cleaner{BaseModel: BaseModel{Id: record.CleanerId}}
		if err := o.Read(cleaner); err == nil {
			record.Cleaner = cleaner
		}
	}

	return record, nil
}

// GetCleaningRecordList 获取保洁记录列表
func GetCleaningRecordList(page, pageSize int, filters map[string]interface{}) ([]*CleaningRecord, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(CleaningRecord))

	// 处理筛选条件
	for k, v := range filters {
		qs = qs.Filter(k, v)
	}

	total, err := qs.Count()
	if err != nil {
		return nil, 0, err
	}

	var records []*CleaningRecord
	_, err = qs.OrderBy("-start_time").Limit(pageSize, (page-1)*pageSize).All(&records)
	if err != nil {
		return nil, 0, err
	}

	// 获取关联数据
	storeIDs := make([]int64, 0)
	venueIDs := make([]int64, 0)
	cleanerIDs := make([]int64, 0)
	for _, record := range records {
		if record.StoreId > 0 {
			storeIDs = append(storeIDs, record.StoreId)
		}
		if record.VenueId > 0 {
			venueIDs = append(venueIDs, record.VenueId)
		}
		if record.CleanerId > 0 {
			cleanerIDs = append(cleanerIDs, record.CleanerId)
		}
	}

	if len(storeIDs) > 0 {
		var stores []Store
		_, err := o.QueryTable(new(Store)).Filter("id__in", storeIDs).All(&stores)
		if err == nil {
			storeMap := make(map[int64]*Store)
			for i := range stores {
				storeMap[stores[i].Id] = &stores[i]
			}
			for _, record := range records {
				if store, ok := storeMap[record.StoreId]; ok {
					record.Store = store
				}
			}
		}
	}

	if len(venueIDs) > 0 {
		var venues []Venue
		_, err := o.QueryTable(new(Venue)).Filter("id__in", venueIDs).All(&venues)
		if err == nil {
			venueMap := make(map[int64]*Venue)
			for i := range venues {
				venueMap[venues[i].Id] = &venues[i]
			}
			for _, record := range records {
				if venue, ok := venueMap[record.VenueId]; ok {
					record.Venue = venue
				}
			}
		}
	}

	if len(cleanerIDs) > 0 {
		var cleaners []Cleaner
		_, err := o.QueryTable(new(Cleaner)).Filter("id__in", cleanerIDs).All(&cleaners)
		if err == nil {
			cleanerMap := make(map[int64]*Cleaner)
			for i := range cleaners {
				cleanerMap[cleaners[i].Id] = &cleaners[i]
			}
			for _, record := range records {
				if cleaner, ok := cleanerMap[record.CleanerId]; ok {
					record.Cleaner = cleaner
				}
			}
		}
	}

	return records, total, nil
}

// UpdateCleaningRecord 更新保洁记录
func UpdateCleaningRecord(cr *CleaningRecord) error {
	o := orm.NewOrm()
	_, err := o.Update(cr)
	return err
}

// DeleteCleaningRecord 删除保洁记录
func DeleteCleaningRecord(id int64) error {
	o := orm.NewOrm()
	_, err := o.QueryTable(new(CleaningRecord)).Filter("id", id).Delete()
	return err
}
